package work.xiaohong.mina.test1;

import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @author Kevin
 * @data 4/25/2022 11:13 AM
 * @description
 **/
@Slf4j
public class MinaClient {

  public static void main(String[] args) {
    IoConnector connector = new NioSocketConnector();
    // 设置超时时间
    connector.setConnectTimeoutMillis(3000);

    // 设置编码过滤器
    connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(
            new TextLineCodecFactory(
                    // 字符集
                    Charset.forName("UTF-8"),
                    // 设置编码器 根据windows里的换行符进行分隔
                    LineDelimiter.WINDOWS.getValue(),
                    // 设置解码器
                    LineDelimiter.WINDOWS.getValue()
            )
    ));

    connector.setHandler(new MyHandler());

    ConnectFuture future = connector.connect(new InetSocketAddress("127.0.0.1", 8080));

    future.awaitUninterruptibly(); // 阻塞等待

    IoSession session = future.getSession();
    session.write("客户端已加入");

    session.getCloseFuture().awaitUninterruptibly(); // 阻塞等待关闭连接

    connector.dispose();


  }

}
